package com.acane.instagram.service.impl;

import com.acane.instagram.mapper.PostMapper;
import com.acane.instagram.pojo.Post;
import com.acane.instagram.pojo.Result;
import com.acane.instagram.pojo.User;
import com.acane.instagram.service.PostService;
import com.acane.instagram.service.TagService;
import com.acane.instagram.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private TagService tagService;

    @Override
    public List<Post> getRecommendPostList(String userId) {
        List<String> recommendPostIds = postMapper.getRecommendPostIds(userId);
        System.out.println("recommendPostIds:----------------------\n " + recommendPostIds);
        if (recommendPostIds.isEmpty()) {
            return new ArrayList<>();
        }
        List<Post> recommendPostList = postMapper.selectRecommendPostList(recommendPostIds);
        for (Post post : recommendPostList) {
            post.setUrls(postMapper.selectPostWithImages(post.getId()));
            post.setUser(userService.getUserById(post.getUserId()));
        }
        return recommendPostList;
    }

    @Override
    public List<Post> getPostListById(String userId) {
        List<Post> postList = postMapper.selectBasicPostsByUserId(userId);
        for (Post post : postList) {
            post.setUrls(postMapper.selectPostWithImages(post.getId()));
            post.setUser(userService.getUserById(post.getUserId()));
        }
        return postList;
    }

    @Override
    public boolean addPost(Post post) {
        if (post.getContent().isBlank() || post.getContent() == null) {
            post.setContent("");
        }
        int i = postMapper.addPost(post);
        // 将url存进数据库
        post.getUrls().forEach(url -> {
            String id = UUID.randomUUID().toString().replace("-", "");
            postMapper.addPostUrl(id, post.getId(), url);
        });
        // 将tag存入数据库
        System.out.println( "存入数据库的tags： " + post.getTags());
        if (post.getTags() != null) {
            post.getTags().forEach(tag -> {
                tagService.saveTags(post.getId(), tag.getId());
            });
        }
        // 添加成功更新用户帖子数量
        User user = userService.getUserById(post.getUserId());
        user.setPostCount(user.getPostCount() + 1);
        userService.updateById(user);
        System.out.println("更新后的user： " + user);
        return i > 0;
    }

    @Override
    public User getUserByPostId(String postId) {
        return postMapper.getUserByPostId(postId);
    }

    @Override
    public Post getPostById(String postId) {
        Post post = postMapper.getPostById(postId);
        System.out.println("---------------------------------------------------------------------------post: " + post);
        post.setUrls(postMapper.selectPostWithImages(post.getId()));
        post.setUser(userService.getUserById(post.getUserId()));
        return post;
    }

    @Override
    public int likePost(String postId) {
        return postMapper.likePost(postId);
    }

    @Override
    public int unlikePost(String postId) {
        return postMapper.unlikePost(postId);
    }

    @Override
    public List<Post> getRecommendVideoList(String userId) {
        List<String> recommendPostIds = postMapper.getRecommendPostIds(userId);
        System.out.println("recommendPostIds:----------------------\n " + recommendPostIds);
        if (recommendPostIds.isEmpty()) {
            return new ArrayList<>();
        }
        List<Post> recommendPostList = postMapper.selectRecommendPostList(recommendPostIds);
        for (Post post : recommendPostList) {
            post.setUrls(postMapper.selectPostWithImages(post.getId()));
            post.setUser(userService.getUserById(post.getUserId()));
        }
        // 获取推荐的视频列表
        return filterVideoPosts(recommendPostList);
    }

    @Override
    public int addCommentCount(String postId) {
        return postMapper.addCommentCount(postId);
    }

    @Override
    public List<Post> searchPost(String keyword) {
        return postMapper.searchPost(keyword);
    }

    @Override
    public List<Post> getPostList() {
        List<Post> postList = postMapper.getPostList();
        // 根据postList 中的 userId 查询用户信息
        for (Post post : postList) {
            post.setUser(userService.getUserById(post.getUserId()));
//            post.setTags(tagService.getTagsByPostId(post.getId()));
        }
        return postList;
    }

    @Override
    public List<Post> getPostListByPage(int pageNum, int pageSize) {
        List<Post> postListByPage = postMapper.getPostListByPage(pageNum, pageSize);
        for (Post post : postListByPage) {
            post.setUrls(postMapper.selectPostWithImages(post.getId()));
            post.setUser(userService.getUserById(post.getUserId()));
            post.setTags(tagService.getTagsByPostId(post.getId()));
        }
        return postListByPage;
    }

    // 筛选出所有 urls 列表大小为 1 且以 .mp4 结尾的 Post 元素
    public List<Post> filterVideoPosts(List<Post> recommendPostList) {
        List<Post> videoPosts = new ArrayList<>();
        for (Post post : recommendPostList) {
            List<String> urls = post.getUrls();
            if (urls.size() == 1 && urls.get(0).endsWith(".mp4")) {
                videoPosts.add(post);
            }
        }
        return videoPosts;
    }

    @Override
    public List<Post> searchPosts(String userName, String nickName, String content,
                                  String startTime, String endTime, int page, int size) {
        // 计算分页偏移量
        int offset = (page - 1) * size;

        List<Post> posts = postMapper.searchPosts(
                userName,
                nickName,
                content,
                startTime,
                endTime,
                offset,
                size
        );

        // 补充用户信息和资源URL
        for (Post post : posts) {
            post.setUser(userService.getUserById(post.getUserId()));
            post.setUrls(postMapper.selectPostWithImages(post.getId()));
        }
        return posts;
    }

    @Override
    public Result passAction(String postId) {
        int i = postMapper.passAction(postId);
        if (i > 0) {
            return Result.success("审核通过，操作成功");
        }
        return Result.failure(401, "操作失败");
    }

    @Override
    public Result failAction(String postId, String reason) {
        int i = postMapper.failAction(postId);
        if (i > 0) {
            return Result.success("审核失败，操作成功");
        }
        return Result.failure(401, "操作失败");
    }
}
